import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { RequestInfo, ResponseOptions } from 'angular-in-memory-web-api';

/**
 * Mock HTTP 日志接口
 */
export interface MockHttpLog {
  id: string;
  timestamp: string;
  request: RequestInfo;
  response: ResponseOptions;
}

/**
 * Mock 帮助服务
 * 提供简单的请求记录功能
 */
@Injectable({
  providedIn: 'root'
})
export class MockHelpService {

  // HTTP 日志存储
  private httpLogsSubject = new BehaviorSubject<MockHttpLog[]>([]);
  
  // HTTP 日志流 - 供组件订阅
  public readonly httpLogs$ = this.httpLogsSubject.asObservable();

  constructor() {}

  /**
   * 记录 HTTP 请求和响应
   * @param reqInfo 请求信息
   * @param responseInfo 响应信息
   */
  logHttp(reqInfo: RequestInfo, responseInfo: ResponseOptions): void {
    const httpLog: MockHttpLog = {
      id: this.generateRequestId(),
      timestamp: new Date().toLocaleTimeString(),
      request: reqInfo,
      response: responseInfo
    };

    // 添加到记录列表
    const currentLogs = this.httpLogsSubject.value;
    const newLogs = [httpLog, ...currentLogs];
    
    // 限制记录数量（最多保留50条）
    if (newLogs.length > 50) {
      newLogs.splice(50);
    }
    
    this.httpLogsSubject.next(newLogs);
  }

  /**
   * 清除所有 HTTP 日志
   */
  clearHttpLogs(): void {
    this.httpLogsSubject.next([]);
  }

  /**
   * 生成请求ID
   */
  private generateRequestId(): string {
    return 'req_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  }
}
